<?php

App::uses('AppController', 'Controller');
App::uses('Contact',       'Model');

class KontaktController extends AppController {
    
    public $uses = array('Contact');
	
	public $pageTitle = 'Kontakt';
    
    public function index() {
        
    }
    
    public function send() {
        $data = $this->data;
        if (! empty($data)) {
            $this->Contact->create($data);
            
            if (! $this->Contact->validates()) {
                $this->setFlash('Uneti podaci nisu validni!');
                $this->set('data', $data);
                return $this->render('index');
            }
            
            $name    = $data['Contact']['name'];
            $email   = $data['Contact']['email'];
            $message = $data['Contact']['message'];
            
            $settings = $this->getSettings();
            $to      = $settings['email'];
            $subject = "Kontakt sa sajta: {$name} ($email)";
            $message = preg_replace('/\r?\n/', '<br>', $message);
            $headers = "Content-Type: text/html; charset=utf-8\n".
                       "From: \"{$name}\"<{$email}>";
            
            if (! mail($to, $subject, $message, $headers)) {
                $this->setFlash('Greška u slanju poruke. Molimo pokušajte ponovo.');
                $this->set('data', $data);
                return $this->render('index');
            }
            
            $this->setFlash('Poruka je uspešno prosleđena.', 'ok');
        }
        
        $this->redirect('index');
    }
    
    public function captcha() {
        $this->autoRender = false;
        
        $buffer  = "qwertyuiopasdfghjklzxcvbnm0123456789";
        $captcha = "";
        for ($i=0; $i<6; $i++) {
            $rand = rand(0, strlen($buffer)-1);
            $captcha .= substr($buffer, $rand, 1);
        }
        $this->Session->write(Contact::$captchaKey, $captcha);
        
        $img  = new Imagick();
        $draw = new ImagickDraw();
        
        $fg = new ImagickPixel('grey');
        $bg = new ImagickPixel('white');
        
        $img->newimage(80, 20, $bg, 'png');
        $draw->setfillcolor($fg);
        $draw->setFont('Harabara.ttf');
        $draw->setFontSize(20);
        $img->annotateimage($draw, 10, 16, 0, $captcha);
        
        header('Content-Type: image/png');
        echo $img;
        die;
    }
    
}
